package cn.edu.pzhu.javaweb.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/updateuserinfo")
public class UserPermissionFilter extends HttpFilter implements Filter {

    private static final long serialVersionUID = 1L;

     public UserPermissionFilter() {
        super();
    }

    public void destroy() {}

    public void init(FilterConfig fConfig) throws ServletException {}

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String sessionUserName = (String) request.getSession().getAttribute("username");
        String targetUserName = request.getParameter("tusername");
        response.setContentType("text/html");

        if(sessionUserName == null){
            response.sendRedirect("login.jsp");
            return;
        } else if (!sessionUserName.equals(targetUserName)) {
            response.getWriter().print("<script>alert('你登录的是" + sessionUserName + "无权限修改" + targetUserName + "的个人信息!');location.href='showuserinfo.jsp';</script>");
            return;
        }else {
            filterChain.doFilter(request, response);
        }
    }
}